package com.jasmine.bjstkserver.server.plan;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.jasmine.bjstkserver.core.config.exception.BjsException;
import com.jasmine.bjstkserver.mapper.PlanMapper;
import com.jasmine.bjstkserver.server.plan.common.PlanTypeEnum;
import com.jasmine.bjstkserver.server.plan.model.PlanDTO;
import com.jasmine.bjstkserver.server.plan.model.PlanEntity;
import com.jasmine.bjstkserver.server.plan.model.PlanReq;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author : jasmineXz
 */
@Service
public class PlanServiceImpl implements PlanService{

    @Autowired
    private PlanMapper planMapper;


    /**
     * 查询列表
     * @param planReq 查询条件
     * @return CARD:list; LINE:map
     */
    @Override
    public Object findList(PlanReq planReq) {
        if (!PlanTypeEnum.contains(planReq.getType())) {
            throw new BjsException("类型错误");
        }
        List<PlanEntity> plans = planMapper.findList(planReq);
        if (PlanTypeEnum.LINE.name().equals(planReq.getType())) {
            return plans.stream().collect(Collectors.groupingBy(PlanEntity::getDay));
        }
        return plans;
    }


    /**
     * 新增
     * @param plan 新增参数
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void insert(PlanDTO plan) {
        if (!PlanTypeEnum.contains(plan.getType())) {
            throw new BjsException("类型错误");
        }

        plan.setGroupId(System.currentTimeMillis());

        if (PlanTypeEnum.CARD.name().equals(plan.getType())) {
            plan.setMonth(null);
            plan.setDay(null);
            planMapper.insertSelective(plan);
        }

        if (PlanTypeEnum.LINE.name().equals(plan.getType())) {
            Date beginDate = DateUtil.parse(plan.getDay());
            if (plan.getRepeat().equals("Y") && plan.getRepeatDay() > 0) {
                for (int i = 0 ; i < plan.getRepeatDay() ; i ++) {
                    plan.setPlanId(null);
                    Date date = DateUtil.offsetDay(beginDate,i);
                    plan.setMonth(DateUtil.format(date, "yyyy-MM"));
                    plan.setDay(DateUtil.format(date, DatePattern.NORM_DATE_PATTERN));
                    planMapper.insertSelective(plan);
                }
            } else {
                plan.setMonth(DateUtil.format(beginDate, "yyyy-MM"));
                plan.setDay(DateUtil.format(beginDate, DatePattern.NORM_DATE_PATTERN));
                planMapper.insertSelective(plan);
            }
        }
    }


    /**
     * 删除
     * @param planId
     */
    @Override
    public void delete(Integer planId) {
        planMapper.deleteByPrimaryKey(planId);
    }

}



















































